var mongoose = require('mongoose');
var User = mongoose.model('User');
var crypto = require('crypto');
var settings = require('../settings');
var validator = require('validator');
var mail = require('../common/mail');
var utility = require('utility');

var generatePwd = function(pwd){
  return crypto.createHash('sha256').update(pwd).digest('base64').toString();
}

var generateAvatar = function(email){
  var url = 'https://gravatar.com/avatar/' + utility.md5(email.toLowerCase()) + '?size=48';
  // www.gravatar.com 被墙
  url = url.replace('www.gravatar.com', 'gravatar.com');
  // 让协议自适应 protocol，使用 `//` 开头
  if (url.indexOf('http:') === 0) {
    url = url.slice(5);
  }
  return url;
}

//用户注册
module.exports.register = function(req,res){
  var pwd = generatePwd(req.body.password.trim());
  var loginname = req.body.username.trim();
  var email = req.body.email.trim();
  var company = req.body.company.trim();
  if(req.body.password.trim().length<6 || req.body.password.trim().length>20){
    return res.send({status: '密码长度范围3-10'})
  }
  if(loginname.length<3 || loginname.length>10){
    return res.send({status: '用户名长度范围3-10'})
  }
  if(!validator.isEmail(email)){
    return res.send({status: '请使用合法的邮箱'})
  }
  User.findOne({"$or": [
    {email:email},
    {name:loginname}
  ]}, function(err, user){
    if(user){
      return res.json({status:"用户名或邮箱已经被注册"})
    }else{
      var newuser = {name:loginname, company: company, email: email, password: pwd}
      newuser.hashId = utility.md5(newuser.email)
      var user = new User(newuser);
      req.session.user = {
        _id:user._id,
        name:user.name,
        email:user.email,
        activated:user.activated,
        admin:user.admin,
        hashId:user.hashId};
      user.save(function(err){
        if(err){console.log(err)}
        res.send({status: 'ok'})
      })
    }
  })
}

//用户登陆
module.exports.login = function(req,res){
  var account = req.body.account;
  console.log(account)
  var pwd = generatePwd(req.body.password)
  User.findOne({"$or":[{name:account},{email:account}]}, function(err, user){
    if(!user){
      return res.json({status:"没有这个用户"})
    }else if(pwd !== user.password){
      return res.json({status:"密码错误"})
    }else{
      req.session.user = {
        _id:user._id,
        name:user.name,
        email:user.email,
        activated:user.activated,
        admin:user.admin,
        hashId:user.hashId};
      return res.json({status: "ok"})
    }
  })
}

//用户注销
module.exports.logout = function(req,res){
  req.session.destroy();
  res.clearCookie(settings.cookieSecret,{path:"/"})
  res.redirect('/')
}

//查看用户信息
exports.getProfile = function(req,res){
  result = {user: req.session.user || null}
  var promise = User.findOne({"name":req.params.username}).populate('cheatsheets').populate('stars').exec();
  promise.then(function(user){
    result.profileUser = user
    res.render('profile', result);
  })
}

//用户编辑个人信息
module.exports.editProfile = function(req,res){
  if(!req.session.user){
    return
  }
  if (req.method == "GET"){
    User.findOne({email:req.session.user.email},function(err,user){
      return res.render("editProfile", {user:user})
    })

  }else if(req.method == "POST"){
    User.findOne({email:req.session.user.email},function(err,user){
      user.company = req.body.company;
      user.description = req.body.description;
      user.avatar = req.body.avatar;
      req.session.user = user;
      user.save(function(err){
        res.send({status: "ok"})
      })
    })
  }
}

module.exports.addAchievement = function(req,res){
  if(!req.session.user){
    return
  }
  User.findOne({email: req.session.user.email}, function(err,user){
    user.achievements.push(req.body.text)
    user.save(function(err){
      res.send({status:"ok"})
    })
  })
}

module.exports.deleteAchievement = function(req, res){
  if(!req.session.user){
    return
  }
  User.findOne({email: req.session.user.email}, function(err,user){
    user.achievements =  user.achievements.filter(function(ac){return ac != req.body.text})
    user.save(function(err){
      res.send({status:"ok"})
    })
  })
}
